package org.developer.dynamic.infra.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
  * 动态数据源路由配置
  *
  * @author yisheng.mikelv@foxmail.com 2020/3/5 15:23
  */
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

    private static Logger logger = LoggerFactory.getLogger(DynamicRoutingDataSource.class);

    //该方法非常关键，从ThreadLocal当前线程获取到需切换到的数据源的 key
    //通过该 key ，再从 DataSource 中切换相应的数据源
    @Override
    protected Object determineCurrentLookupKey() {
        String dataSourceName = DynamicDataSourceContextHolder.getDataSourceRouterKey();
        logger.info("当前数据源是：{}",dataSourceName);
        return DynamicDataSourceContextHolder.getDataSourceRouterKey();
    }
}
